// 添加好友功能实现 - 重构版本

// ========== 全局变量定义 ==========
let friendRequests = [];
let searchResults = [];

// ========== 核心函数定义 ==========

// 初始化事件监听
function initAddFriendEvents() {
    console.log('初始化添加好友事件');
    
    // 打开添加好友模态框
    $('#add-friend-page-btn').off('click').on('click', openAddFriendModal);
    
    // 关闭添加好友模态框
    $('#close-add-friend-modal').off('click').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('点击关闭添加好友模态框按钮');
        closeAddFriendModal();
    });
    
    // 搜索用户
    $('#add-friend-search-btn').off('click').on('click', function(e) {
        e.stopPropagation();
        e.preventDefault();
        searchUsers();
    });
    
    $('#add-friend-search-input').off('keypress').on('keypress', function(e) {
        if (e.which === 13) {
            e.stopPropagation();
            e.preventDefault();
            searchUsers();
        }
    });
    
    // 点击模态框外部关闭
    $('#add-friend-modal').off('click').on('click', function(e) {
        if (e.target === this) {
            console.log('点击添加好友模态框外部');
            closeAddFriendModal();
        }
    });
    
    // 阻止模态框内容点击事件冒泡
    $('.modal').off('click').on('click', function(e) {
        e.stopPropagation();
    });

    // 刷新好友请求
    $('#refresh-friend-requests').off('click').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('手动刷新好友请求');
        loadFriendRequests();
    });

    // 打开好友请求模态框
    $('#friend-requests-btn').off('click').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('点击好友请求按钮');
        openFriendRequestsModal();
    });
    
    // 关闭好友请求模态框
    $('#close-friend-requests-modal').off('click').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('点击关闭好友请求模态框按钮');
        closeFriendRequestsModal();
    });
    
    // 点击好友请求模态框外部关闭
    $('#friend-requests-modal').off('click').on('click', function(e) {
        if (e.target === this) {
            console.log('点击好友请求模态框外部');
            closeFriendRequestsModal();
        }
    });
    
    // 阻止好友请求模态框内容点击事件冒泡
    $('#friend-requests-modal .modal').off('click').on('click', function(e) {
        e.stopPropagation();
    });
}

// 检查当前用户会话
function checkUserSession() {
    console.log('当前页面会话信息:');
    console.log('- Document cookie:', document.cookie);
    console.log('- 当前URL:', window.location.href);
    
    // 尝试获取当前用户信息（如果存在）
    if (window.getCurrentUser) {
        const user = window.getCurrentUser();
        console.log('当前用户:', user);
    }
}

// 检查事件绑定状态
function checkEventBindings() {
    console.log('=== 事件绑定状态检查 ===');
    console.log('添加好友按钮:', $('#add-friend-page-btn').length > 0 ? '存在' : '不存在');
    console.log('好友请求按钮:', $('#friend-requests-btn').length > 0 ? '存在' : '不存在');
    console.log('=== 事件绑定检查结束 ===');
}

// 打开添加好友模态框
function openAddFriendModal() {
    console.log('打开添加好友模态框');
    $('#add-friend-modal').removeClass('hide').show();
    $('#search-user-input').val('').focus();
    clearSearchResults();
    
    // 强制显示检查
    setTimeout(() => {
        console.log('模态框显示状态:', $('#add-friend-modal').is(':visible'));
        console.log('模态框CSS显示:', $('#add-friend-modal').css('display'));
    }, 100);
}

// 关闭添加好友模态框
function closeAddFriendModal() {
    console.log('执行关闭模态框');
    $('#add-friend-modal').addClass('hide');
    clearSearchResults();
}

// 清空搜索结果
function clearSearchResults() {
    $('#add-friend-results').empty().hide();
    $('#add-friend-no-results').show().html(`
        <div style="text-align: center; color: #7a9a9a; padding: 40px;">
            <i class="fas fa-search" style="font-size: 48px; margin-bottom: 16px;"></i>
            <p>请输入用户名搜索好友</p>
        </div>
    `);
    searchResults = [];
}

// 搜索用户
function searchUsers() {
    const username = $('#add-friend-search-input').val().trim();
    console.log('搜索用户名:', username);
    
    if (!username) {
        alert('请输入要搜索的用户名');
        return;
    }

    // 显示加载状态
    $('#add-friend-no-results').html(`
        <div class="loading">
            <i class="fas fa-spinner fa-spin"></i>
            <p>搜索中...</p>
        </div>
    `).show();
    
    $('#add-friend-results').hide();

    // 发送搜索请求
    $.ajax({
        url: `/findAllFriends?name=${encodeURIComponent(username)}`,
        type: 'GET',
        success: function(response) {
            console.log('完整搜索响应:', response);
            
            if (response.success && Array.isArray(response.data)) {
                displaySearchResults(response.data);
            } else {
                $('#add-friend-no-results').html(`
                    <div style="text-align: center; color: #f44336; padding: 20px;">
                        <i class="fas fa-exclamation-triangle"></i>
                        <p>${response.message || '搜索失败'}</p>
                    </div>
                `).show();
            }
        },
        error: function(xhr, status, error) {
            console.error('搜索用户失败:', error);
            $('#add-friend-no-results').html(`
                <div style="text-align: center; color: #f44336; padding: 20px;">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>搜索失败，请重试</p>
                </div>
            `).show();
        }
    });
}

// 显示搜索结果
function displaySearchResults(users) {
    console.log('收到的用户数据:', users);
    
    if (!Array.isArray(users)) {
        console.error('users 不是数组:', users);
        $('#add-friend-no-results').html(`
            <div style="text-align: center; color: #f44336; padding: 40px;">
                <i class="fas fa-exclamation-triangle"></i>
                <p>数据格式错误</p>
            </div>
        `).show();
        $('#add-friend-results').hide();
        return;
    }
    
    searchResults = users;
    
    if (searchResults.length === 0) {
        $('#add-friend-no-results').html(`
            <div style="text-align: center; color: #7a9a9a; padding: 40px;">
                <i class="fas fa-search" style="font-size: 48px; margin-bottom: 16px;"></i>
                <p>未找到匹配的用户</p>
            </div>
        `).show();
        $('#add-friend-results').hide();
        return;
    }

    $('#add-friend-no-results').hide();
    const $resultsContainer = $('#add-friend-results').empty();
    
    console.log('开始渲染搜索结果，数量:', searchResults.length);

    searchResults.forEach(user => {
        console.log('处理用户:', user);
        
        // 确保用户数据有效
        if (!user || !user.userId) {
            console.warn('无效的用户数据:', user);
            return;
        }
        
        // 使用更安全的方式创建元素
        const userItem = document.createElement('div');
        userItem.className = 'user-result-item';
        userItem.setAttribute('data-user-id', user.userId);
        
        userItem.innerHTML = `
            <div class="user-avatar">
                ${user.username ? user.username.charAt(0).toUpperCase() : 'U'}
            </div>
            <div class="user-info">
                <div class="user-name">${user.username || '未知用户'}</div>
                <input type="text" class="reason-input" placeholder="请输入添加好友理由..." maxlength="50">
            </div>
            <button class="add-friend-btn" data-username="${user.username}">
                添加好友
            </button>
        `;

        // 绑定添加好友事件
        const addBtn = userItem.querySelector('.add-friend-btn');
        addBtn.addEventListener('click', function() {
            const reasonInput = userItem.querySelector('.reason-input');
            const reason = reasonInput.value.trim();
            sendFriendRequest(user.username, reason);
        });

        $resultsContainer.append(userItem);
    });
    
    // 显示结果容器
    $resultsContainer.show();
    
    console.log('渲染完成，容器中的项目数:', $resultsContainer.children().length);
}

function sendFriendRequest(username, reason) {
    if (!username) {
        alert('用户信息错误');
        return;
    }

    const $btn = $(`.add-friend-btn[data-username="${username}"]`);
    $btn.prop('disabled', true).text('发送中...');

    // 构建请求URL
    let url = `/addFriend?name=${encodeURIComponent(username)}`;
    if (reason) {
        url += `&reason=${encodeURIComponent(reason)}`;
    }

    $.ajax({
        url: url,
        type: 'GET',
        success: function(response) {
            console.log('发送好友请求响应:', response);
            
            if (response.success) {
                alert('好友请求发送成功！');
                $btn.text('已发送').css('background', '#ccc');
                closeAddFriendModal();
            } else {
                alert('发送好友请求失败：' + (response.message || '未知错误'));
                $btn.prop('disabled', false).text('添加好友');
            }
        },
        error: function(xhr, status, error) {
            console.error('发送好友请求失败:', error);
            alert('发送好友请求失败，请重试');
            $btn.prop('disabled', false).text('添加好友');
        }
    });
}

// 打开好友请求模态框
function openFriendRequestsModal() {
    console.log('打开好友请求模态框');
    $('#friend-requests-modal').removeClass('hide').show();
    loadFriendRequests();
    
    // 强制显示检查
    setTimeout(() => {
        console.log('好友请求模态框显示状态:', $('#friend-requests-modal').is(':visible'));
        console.log('好友请求模态框CSS显示:', $('#friend-requests-modal').css('display'));
    }, 100);
}

// 关闭好友请求模态框
function closeFriendRequestsModal() {
    console.log('执行关闭好友请求模态框');
    $('#friend-requests-modal').addClass('hide');
}

// 加载好友请求
function loadFriendRequests() {
    console.log('开始加载好友请求，当前用户会话:', document.cookie);
    
    $.ajax({
        url: '/getFriendRequest',
        type: 'GET',
        success: function(response) {
            console.log('好友请求API完整响应:', response);
            console.log('响应success:', response.success);
            console.log('响应message:', response.message);
            console.log('响应data类型:', typeof response.data);
            
            if (response.success) {
                if (Array.isArray(response.data)) {
                    friendRequests = response.data;
                    console.log('加载到的好友请求数量:', friendRequests.length);
                    console.log('具体请求数据:', friendRequests);
                    
                    // 检查每个请求的字段
                    friendRequests.forEach((req, index) => {
                        console.log(`请求 ${index}:`, {
                            requestId: req.requestId,
                            fromUserId: req.fromUserId,
                            toUserId: req.toUserId,
                            fromUserName: req.fromUserName,
                            reason: req.reason,
                            status: req.status
                        });
                    });
                    
                    displayFriendRequests();
                    updateFriendRequestBadge();
                } else {
                    console.error('好友请求数据不是数组:', response.data);
                    friendRequests = [];
                    displayFriendRequests();
                }
            } else {
                console.error('获取好友请求失败:', response.message);
                friendRequests = [];
                displayFriendRequests();
            }
        },
        error: function(xhr, status, error) {
            console.error('加载好友请求失败:', error);
            console.log('状态码:', xhr.status);
            console.log('响应文本:', xhr.responseText);
            friendRequests = [];
            displayFriendRequests();
        }
    });
}

// 显示好友请求
function displayFriendRequests() {
    const $requestsContainer = $('#friend-requests-list');
    
    console.log('显示好友请求，数量:', friendRequests.length);
    
    if (!friendRequests || friendRequests.length === 0) {
        $requestsContainer.html(`
            <div class="no-requests">
                <i class="fas fa-user-friends"></i>
                <p>暂无好友请求</p>
                <p class="sub-text">当有人添加您为好友时，请求会显示在这里</p>
            </div>
        `);
        console.log('没有好友请求可显示');
        return;
    }

    let html = '';
    friendRequests.forEach(request => {
        console.log('处理单个请求:', request);
        
        // 确保请求数据有效且有必要的字段
        if (!request || !request.requestId) {
            console.warn('无效的好友请求数据:', request);
            return;
        }
        
        // 确保字段名正确
        const requestId = request.requestId || request.id;
        const fromUserName = request.fromUserName || request.username || '未知用户';
        const reason = request.reason || '请求添加您为好友';
        
        // 获取姓氏首字母
        const lastName = fromUserName.charAt(0).toUpperCase();
        
        console.log(`渲染请求: ID=${requestId}, 来自=${fromUserName}, 理由=${reason}`);
        
        // 使用新的HTML结构 - 确保布局正确
        html += `
            <div class="friend-request-item" data-request-id="${requestId}">
                <div class="request-avatar">${lastName}</div>
                <div class="request-content">
                    <div class="request-user-info">
                        <div class="request-username">${fromUserName}</div>
                        <div class="request-reason" title="${reason}">
                            ${reason}
                        </div>
                    </div>
                    <div class="request-actions">
                        <button class="accept-btn" data-request-id="${requestId}">
                            <i class="fas fa-check"></i> 接受
                        </button>
                        <button class="ignore-btn" data-request-id="${requestId}">
                            <i class="fas fa-times"></i> 忽略
                        </button>
                    </div>
                </div>
            </div>
        `;
    });

    $requestsContainer.html(html);
    console.log('生成的HTML长度:', html.length);

    // 绑定事件
    $('.accept-btn').off('click').on('click', function() {
        const requestId = $(this).data('request-id');
        console.log('点击同意请求:', requestId);
        acceptFriendRequest(requestId);
    });

    $('.ignore-btn').off('click').on('click', function() {
        const requestId = $(this).data('request-id');
        console.log('点击忽略请求:', requestId);
        rejectFriendRequest(requestId);
    });
}

// 同意好友请求
function acceptFriendRequest(requestId) {
    $.ajax({
        url: `/acceptFriend?friendId=${requestId}`,
        type: 'GET',
        success: function(response) {
            console.log('接受好友请求响应:', response);
            
            if (response.success) {
                // 从列表中移除
                $(`.friend-request-item[data-request-id="${requestId}"]`).remove();
                friendRequests = friendRequests.filter(req => req.requestId !== requestId);
                
                if (friendRequests.length === 0) {
                    displayFriendRequests();
                }
                
                updateFriendRequestBadge();
                alert('已同意好友请求');
                
                // 刷新好友列表
                if (window.refreshFriendList) {
                    window.refreshFriendList();
                }
            } else {
                alert('操作失败：' + (response.message || '未知错误'));
            }
        },
        error: function(xhr, status, error) {
            console.error('同意好友请求失败:', error);
            alert('操作失败，请重试');
        }
    });
}

// 忽略好友请求
function rejectFriendRequest(requestId) {
    $.ajax({
        url: `/rejectFriend?friendId=${requestId}`,
        type: 'GET',
        success: function(response) {
            console.log('拒绝好友请求响应:', response);
            
            if (response.success) {
                // 从列表中移除
                $(`.friend-request-item[data-request-id="${requestId}"]`).remove();
                friendRequests = friendRequests.filter(req => req.requestId !== requestId);
                
                if (friendRequests.length === 0) {
                    displayFriendRequests();
                }
                
                updateFriendRequestBadge();
            } else {
                alert('操作失败：' + (response.message || '未知错误'));
            }
        },
        error: function(xhr, status, error) {
            console.error('忽略好友请求失败:', error);
            alert('操作失败，请重试');
        }
    });
}

// 更新好友请求徽章
function updateFriendRequestBadge() {
    const $badge = $('#friend-requests-badge');
    const count = friendRequests.length;
    
    if (count > 0) {
        $badge.removeClass('hide').text(count > 99 ? '99+' : count);
    } else {
        $badge.addClass('hide');
    }
}

// WebSocket 处理好友请求（在线情况）
function initWebSocketFriendHandler() {
    if (window.ws) {
        window.ws.onmessage = function(event) {
            try {
                const message = JSON.parse(event.data);
                
                // 处理好友请求推送
                if (message.type === 'friend_request') {
                    // 添加到请求列表
                    friendRequests.push(message.data);
                    displayFriendRequests();
                    updateFriendRequestBadge();
                    
                    // 显示通知
                    if (!$('#friend-requests-modal').is(':visible')) {
                        showFriendRequestNotification(message.data);
                    }
                }
            } catch (e) {
                console.error('解析WebSocket消息失败:', e);
            }
        };
    }
}

// 显示好友请求通知
function showFriendRequestNotification(request) {
    // 可以在这里实现桌面通知或弹窗提示
    console.log('收到好友请求:', request);
}

// ========== 初始化代码 ==========

// 只有一个文档加载完成事件
$(document).ready(function() {
    console.log('文档加载完成，开始初始化添加好友功能');
    
    // 初始化步骤
    checkUserSession();
    initAddFriendEvents();
    initWebSocketFriendHandler();
    
    // 延迟检查事件绑定
    setTimeout(checkEventBindings, 500);
    
    // 页面加载时获取好友请求
    setTimeout(function() {
        console.log('页面加载完成，自动加载好友请求');
        loadFriendRequests();
    }, 2000);
});

// ========== 兼容性代码 ==========

// 确保全局可用（如果其他脚本需要调用这些函数）
window.initAddFriendEvents = initAddFriendEvents;
window.loadFriendRequests = loadFriendRequests;
window.openFriendRequestsModal = openFriendRequestsModal;